#!/bin/env python

import time
import cv2
import numpy as np

windowName = "dilate"

cv2.namedWindow(windowName, cv2.WINDOW_NORMAL)
cv2.namedWindow("raw", cv2.WINDOW_NORMAL)


# 形态学开运算 = 腐蚀 + 膨胀 = 去除图形外部的噪声
op = cv2.MORPH_OPEN 
pic_path = "../resource/pic/img_008.jpg"

# # 形态学闭运算 = 膨胀 + 腐蚀 = 去除图形内部的噪声
# op = cv2.MORPH_CLOSE
# pic_path = "../resource/pic/img_009.jpg"

# # 形态学梯度 = 膨胀 - 腐蚀 = 边缘
# op = cv2.MORPH_GRADIENT 
# pic_path = "../resource/pic/img_008.jpg"

# # 顶帽操作 = 原图 - 开运算 = 获取图形外部的噪声
# op = cv2.MORPH_TOPHAT 
# pic_path = "../resource/pic/img_008.jpg"

# # 黑帽操作 = 原图 - 闭运算 = 获取图形内部的噪声
# op = cv2.MORPH_BLACKHAT 
# pic_path = "../resource/pic/img_009.jpg"




pic1_gray = cv2.imread(pic_path, cv2.IMREAD_GRAYSCALE)

cv2.resizeWindow("raw", pic1_gray.shape[1],  pic1_gray.shape[0])
cv2.resizeWindow(windowName, pic1_gray.shape[1],  pic1_gray.shape[0])

cv2.imshow("raw", pic1_gray)

def trackbarCallback(value):
    print(value)

new_operate1 = 3
new_operate2 = 1

old_operate1 = new_operate1
old_operate2 = new_operate2

cv2.createTrackbar('operate1', windowName, old_operate1, 10, trackbarCallback)
cv2.createTrackbar('operate2', windowName, old_operate2, 5, trackbarCallback)

# 获取形态学卷积核
M = cv2.getStructuringElement(cv2.MORPH_RECT, (old_operate1, old_operate1))
img = cv2.morphologyEx(pic1_gray, op, M, iterations=old_operate2)

cv2.imshow(windowName, img)

while True:
    if cv2.waitKey(1) == ord('q'):
        break

    new_operate1 = cv2.getTrackbarPos('operate1', windowName)
    new_operate2 = cv2.getTrackbarPos('operate2', windowName)

    if new_operate1 != old_operate1 and new_operate1 % 2 == 1 and new_operate1 > 1:
        print("operate1:", new_operate1)
        old_operate1 = new_operate1
        M = cv2.getStructuringElement(cv2.MORPH_RECT, (old_operate1, old_operate1))
        img = cv2.morphologyEx(pic1_gray, op, M, iterations=old_operate2)
        cv2.imshow(windowName, img)

    if new_operate2 != old_operate2:
        print("operate2:", new_operate2)
        old_operate2 = new_operate2
        M = cv2.getStructuringElement(cv2.MORPH_RECT, (old_operate1, old_operate1))
        img = cv2.morphologyEx(pic1_gray, op, M, iterations=old_operate2)
        cv2.imshow(windowName, img)

print('销毁窗口')
cv2.destroyAllWindows()
